import logging

from flask import session, current_app, render_template, jsonify, request, g

from info import constants
from info.models import User, News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue


@index_blue.route('/newslist')
def news_list():
    """
    思路分析:
    1.获取参数
    2.转换参数类型
    3.查询数据库
    4.获取到分页对象中的内容
    5.将对象列表,转成字典列表
    6.返回响应,携带数据
    :return:
    """
    # 1.获取参数
    cid = request.args.get("cid", 1)
    page = request.args.get("page", 1)
    per_page = request.args.get("per_page", 10)
    # 2.转换参数类型
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10
    # 3.查询数据库
    try:
        filters = []
        if cid != '1':
            filters.append(News.category_id == cid)
        # try:
        #     print(filters[0])
        # except Exception as e:
        #     print(e)
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻失败")
    # 4.获取到分页对象中的内容
    currentPage = paginate.page
    totalPage = paginate.pages
    items = paginate.items
    # 5.将对象列表,转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())
    # 6.返回响应,携带数据
    return jsonify(errno=RET.OK, errmsg="查询成功", totalPage=totalPage, currentPage=currentPage, newsList=news_list)


@index_blue.route('/')
@user_login_data
def hello():
    user_id = session.get('user_id')
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻失败")
    clicks_news_list = []
    for item in news_list:
        clicks_news_list.append(item.to_dict())
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_list = []
    for cate in categories:
        category_list.append(cate.to_dict())

    data = {
        "user_info": g.user.to_dict() if g.user else "",
        'clicks_news_list': clicks_news_list,
        'category_list': category_list
    }
    return render_template('news/index.html', data=data)


@index_blue.route('/favicon.ico')
def get_web_lofo():
    return current_app.send_static_file("news/favicon.ico")
